package com.xuecheng.publish.listener;

import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.common.util.JsonUtil;
import com.xuecheng.common.util.StringUtil;
import com.xuecheng.publish.common.constant.CoursePublishErrorCode;
import com.xuecheng.publish.entity.CoursePubMsg;
import com.xuecheng.publish.service.CoursePubService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * <p></p>
 *
 * @Description:
 */
@Slf4j
@Component
public class PublishPageConsumer {

    @Autowired
    private CoursePubService coursePubService;

    /*
        # 课程发布 交换机名称
        course.publish.exchange = course_pub.direct
        # 课程发布 页面生成队列名称
        course.publish.queue = course_page.queue
        course.publish.routingkey= publish.course
    * */
    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(value="${course.publish.queue}"),
            exchange = @Exchange(value = "${course.publish.exchange}"),
            key = "${course.publish.routingkey}"
    )})
    public void getpublishMsg(String jsonString) {

        log.info("消费方发布页面已经开始执行：{}",jsonString);

        //int i = 1 / 0;
        
        
        /*
        * 操作步骤：
        *   1.接受消息
        *   2.将消息进行转换生成CoursePubMsg
        *   3.调用service层，完成本地事务的操作
        * */

        // 1.接受消息
        if (StringUtil.isBlank(jsonString)) {
            ExceptionCast.cast(CoursePublishErrorCode.E_1200602);
        }

        // 2.将消息进行转换生成CoursePubMsg
        CoursePubMsg coursePubMsg = null;
        try {
            coursePubMsg = JsonUtil.jsonToObject(jsonString, CoursePubMsg.class);
        } catch (Exception e) {
            log.error("发布消息转换失败：{},msg:{}",e.getMessage(),jsonString);
            ExceptionCast.castWithException(CoursePublishErrorCode.E_1200603,e);
        }

        // 3.调用service层，完成本地事务的操作
        coursePubService.publishPage(coursePubMsg);

    }
}